package com.zvfe.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zvfe.common.QueryPageParam;
import com.zvfe.common.R;
import com.zvfe.pojo.Dto.RecordDto;
import com.zvfe.pojo.Goods;
import com.zvfe.pojo.Record;
import com.zvfe.service.GoodsService;
import com.zvfe.service.RecordService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wny
 * @since 2023-07-06
 */
@RestController
@RequestMapping("/record")
public class RecordController {
    @Autowired
    private RecordService recordService;

    @Autowired
    private GoodsService goodsService;

    @PostMapping("/listPage")
    public R listPage(@RequestBody QueryPageParam param) {
        HashMap hm = param.getParam();
        Page<Record> page = new Page<>();
        page.setCurrent(param.getPageNum());
        page.setSize(param.getPageSize());
        String name = (String) hm.get("name");  //搜索关键词
        String goodstype = (String) hm.get("goodstype"); //种类id
        String roleId = (String) hm.get("roleId");  //权限id
        String userId = (String) hm.get("userId");  //当前用户id
        String storage = (String) hm.get("storage"); //仓库id
        QueryWrapper<Record> wrapper = new QueryWrapper<>();
        wrapper.apply(" a.goods=b.id and b.storage=c.id and b.goodsType=d.id");
        if("2".equals(roleId)){
            wrapper.apply(" a.userId="+userId);
        }
        wrapper.like(StringUtils.isNotEmpty(name),"b.name",name)
                .eq(StringUtils.isNotEmpty(storage),"c.id",storage)
                .eq(StringUtils.isNotEmpty(goodstype    ),"d.id",goodstype)
                .orderByAsc("a.id");

        IPage<Record> result = recordService.pageCC(page, wrapper);
        return R.success(result.getRecords(), result.getTotal());
    }

    //商品入库操作(1.新增record数据 2.修改goods的数据-需要更改count数量)
    @PostMapping("/add")
    public R doIn(@RequestBody Record record){
        String action = record.getAction();
        Goods goods = goodsService.getById(record.getGoods());
        int incount=record.getCount();
        //出库
        if ("2".equals(action)){
            incount= -incount;
            record.setCount(incount);
        }
        int newCount = goods.getCount()+incount;
        goods.setCount(newCount);
        goodsService.updateById(goods);
        return recordService.save(record)?R.success():R.err();
    }
}
